package com.yyw.h5gameqianguoshu;

import android.Manifest;
import android.app.Activity;

import android.webkit.JavascriptInterface;
import android.widget.Toast;


import com.hjq.permissions.OnPermission;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.jf.permissonutils.PermissionUtils;
import com.yayawan.callback.YYWAnimCallBack;
import com.yayawan.callback.YYWApiCallback;
import com.yayawan.callback.YYWExitCallback;
import com.yayawan.callback.YYWPayCallBack;
import com.yayawan.callback.YYWUserCallBack;
import com.yayawan.domain.YYWOrder;
import com.yayawan.domain.YYWUser;
import com.yayawan.main.Kgame;
import com.yayawan.utils.DeviceUtil;
import com.yayawan.utils.Yayalog;


import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;



public class GameApi {

    public static boolean isloginsuc = false;

    public static boolean isloginisshow = false;
    public Activity mActivity;

    public X5WebView mWebView;

    public GameApi(Activity mactivity, X5WebView webview) {
        this.mActivity = mactivity;
        this.mWebView = webview;
    }

    @JavascriptInterface
    public void anmi() {

        Kgame.getInstance().anim(mActivity, new YYWAnimCallBack() {

            @Override
            public void onAnimSuccess(String arg0, Object arg1) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onAnimFailed(String arg0, Object arg1) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onAnimCancel(String arg0, Object arg1) {
                // TODO Auto-generated method stub

            }
        });
    }


    @JavascriptInterface
    public void login() {
        System.out.println("login======调用本地登录");

        String isneedpermisson = DeviceUtil.getGameInfo(mActivity, "isneedpermisson");
        if (isneedpermisson.equals("yes")) {


            //检查权限进行登录，有权限才可以登录

            if (!(PermissionUtils.checkPermission(mActivity, Manifest.permission.READ_EXTERNAL_STORAGE)
                    && PermissionUtils.checkPermission(mActivity, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    && PermissionUtils.checkPermission(mActivity, Manifest.permission.READ_PHONE_STATE))) {

                Toast.makeText(mActivity, "亲爱的玩家，请到应用 管理中给予app必要权限", Toast.LENGTH_LONG).show();
                // TODO Auto-generated method stub
                Yayalog.loger("请求权限对话框按钮按下");

                cherkPermission();

            } else {


                //isloginsuc=true;
                System.out.println("login调用本地登录");
                if (isloginisshow) {
                    System.out.println("login已经展示了登陆登录");
                    return;
                }
                isloginisshow = true;
                //Toast.makeText(mActivity, "调用登陆了", 0).show();
                Kgame.getInstance().login(mActivity, new YYWUserCallBack() {

                    @Override
                    public void onLogout(Object arg0) {
                        // TODO Auto-generated method stub
                        mWebView.loadUrl("javascript:ApiGameCallBack.loginOut()");
                        isloginsuc = false;
                        isloginisshow = false;
                    }

                    @Override
                    public void onLoginSuccess(YYWUser user, Object arg1) {
                        // TODO Auto-generated method stub
                        System.out.println("login调用本地登陆成功");
                        isloginisshow = false;
                        isloginsuc = true;
                        JSONObject userjson = new JSONObject();
                        try {

                            userjson.put("uid", user.uid);
                            userjson.put("username", user.userName);
                            userjson.put("token", user.token);
                            //{"uid":"4020895875512481162","username":"kk1411930146","token":"07518edabc40d63ec2acdae6b90924a4"}
                            Yayalog.loger("Gameapi登陆成功：" + userjson.toString());
                            //System.out.println("Gameapi登陆成功："+userjson.toString());
                            mWebView.loadUrl("javascript:ApiGameCallBack.loginSuc(" + userjson.toString() + ")");

                        } catch (JSONException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }

                    }

                    @Override
                    public void onLoginFailed(String arg0, Object arg1) {
                        // TODO Auto-generated method stub
                        Yayalog.loger("onLoginFailed");
                        isloginsuc = false;
                        isloginisshow = false;
                        mWebView.loadUrl("javascript:ApiGameCallBack.loginFail()");
                    }

                    @Override
                    public void onCancel() {
                        // TODO Auto-generated method stub
                        Yayalog.loger("onLoginFailed");
                        mWebView.loadUrl("javascript:ApiGameCallBack.loginFail()");
                        isloginsuc = false;
                        isloginisshow = false;
                    }
                });

            }

        } else {
            //检查权限进行登录，申请权限


            cherkPermissionNoNeedPermission();

            //isloginsuc=true;
            System.out.println("login调用本地登录");
            if (isloginisshow) {
                System.out.println("login已经展示了登陆登录");
                return;
            }
            isloginisshow = true;
            //Toast.makeText(mActivity, "调用登陆了", 0).show();
            Kgame.getInstance().login(mActivity, new YYWUserCallBack() {

                @Override
                public void onLogout(Object arg0) {
                    // TODO Auto-generated method stub
                    mWebView.loadUrl("javascript:ApiGameCallBack.loginOut()");
                    isloginsuc = false;
                    isloginisshow = false;
                }

                @Override
                public void onLoginSuccess(YYWUser user, Object arg1) {
                    // TODO Auto-generated method stub
                    System.out.println("login调用本地登陆成功");
                    isloginisshow = false;
                    isloginsuc = true;
                    JSONObject userjson = new JSONObject();
                    try {

                        userjson.put("uid", user.uid);
                        userjson.put("username", user.userName);
                        userjson.put("token", user.token);
                        //{"uid":"4020895875512481162","username":"kk1411930146","token":"07518edabc40d63ec2acdae6b90924a4"}
                        Yayalog.loger("Gameapi登陆成功：" + userjson.toString());
                        //System.out.println("Gameapi登陆成功："+userjson.toString());
                        mWebView.loadUrl("javascript:ApiGameCallBack.loginSuc(" + userjson.toString() + ")");

                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                }

                @Override
                public void onLoginFailed(String arg0, Object arg1) {
                    // TODO Auto-generated method stub
                    Yayalog.loger("onLoginFailed");
                    isloginsuc = false;
                    isloginisshow = false;
                    mWebView.loadUrl("javascript:ApiGameCallBack.loginFail()");
                }

                @Override
                public void onCancel() {
                    // TODO Auto-generated method stub
                    Yayalog.loger("onLoginFailed");
                    mWebView.loadUrl("javascript:ApiGameCallBack.loginFail()");
                    isloginsuc = false;
                    isloginisshow = false;
                }
            });

        }




	}


    public void cherkPermissionNoNeedPermission(){
       // Toast.makeText(mActivity,"为了保护游戏账号，游戏更新需要下载游戏到储存卡！\n 麻烦给予一下存储卡权限吧！",Toast.LENGTH_LONG).show();
        XXPermissions.with(mActivity)
                // 可设置被拒绝后继续申请，直到用户授权或者永久拒绝
                //.constantRequest()
                // 支持请求6.0悬浮窗权限8.0请求安装权限
                //.permission(Permission.SYSTEM_ALERT_WINDOW, Permission.REQUEST_INSTALL_PACKAGES)
                // 不指定权限则自动获取清单中的危险权限
                .permission(Permission.READ_EXTERNAL_STORAGE, Permission.WRITE_EXTERNAL_STORAGE,Permission.READ_PHONE_STATE)
                .request(new OnPermission() {

                    @Override
                    public void hasPermission(List<String> granted, boolean isAll) {

                    }

                    @Override
                    public void noPermission(List<String> denied, boolean quick) {

                    }
                });

    }

	public void cherkPermission(){

        Toast.makeText(mActivity,"为了保护游戏账号，游戏更新需要下载游戏到储存卡！\n 麻烦给予一下存储卡权限吧！",Toast.LENGTH_LONG).show();
        XXPermissions.with(mActivity)
                // 可设置被拒绝后继续申请，直到用户授权或者永久拒绝
                //.constantRequest()
                // 支持请求6.0悬浮窗权限8.0请求安装权限
                //.permission(Permission.SYSTEM_ALERT_WINDOW, Permission.REQUEST_INSTALL_PACKAGES)
                // 不指定权限则自动获取清单中的危险权限
                .permission(Permission.READ_EXTERNAL_STORAGE, Permission.WRITE_EXTERNAL_STORAGE,Permission.READ_PHONE_STATE)
                .request(new OnPermission() {

                    @Override
                    public void hasPermission(List<String> granted, boolean isAll) {
                            if (isAll){
                                login();
                            }
                    }

                    @Override
                    public void noPermission(List<String> denied, boolean quick) {

                    }
                });




	}
	public  void showToast(String msg){
		Toast.makeText(mActivity,msg,Toast.LENGTH_LONG).show();
	}
	@JavascriptInterface
	public void ceshi() {
	
	}
	
	@JavascriptInterface
	public void pay(String orderid,String goods,String money,String ext,String gppdid) {
	
		YYWOrder order = new YYWOrder(orderid, goods,
				Long.parseLong(money), ext);
		Kgame.getInstance().pay(mActivity, order, new YYWPayCallBack() {
			
			@Override
			public void onPaySuccess(YYWUser arg0, YYWOrder arg1, Object arg2) {
				// TODO Auto-generated method stub
				mWebView.loadUrl("javascript:ApiGameCallBack.shareSuc()");
			}
			
			@Override
			public void onPayFailed(String arg0, Object arg1) {
				// TODO Auto-generated method stub
				mWebView.loadUrl("javascript:ApiGameCallBack.shareFail()");
			}
			
			@Override
			public void onPayCancel(String arg0, Object arg1) {
				// TODO Auto-generated method stub
				mWebView.loadUrl("javascript:ApiGameCallBack.shareFail()");
			}
		});
		
	}
	
	@JavascriptInterface
	public void exit() {
		Kgame.getInstance().exit(mActivity, new YYWExitCallback() {
			
			@Override
			public void onExit() {
				// TODO Auto-generated method stub
				mWebView.loadUrl("javascript:ApiGameCallBack.exitSuc()");
			}
		});
	}
	
	
	@JavascriptInterface
	public void setdata( String roleId, String roleName,String roleLevel,String zoneId,String zoneName,String roleCTime,String ext) {
		Yayalog.loger("gameapisetdata:");
		Kgame.getInstance().setData(mActivity, roleId, roleName, roleLevel, zoneId, zoneName, roleCTime, ext);
	}

    @JavascriptInterface
    public void realName() {
        Kgame.getInstance().doGetVerifiedInfo(mActivity, new YYWApiCallback() {
            @Override
            public void onVerifySuccess(String s) {
                //返回实名认证  结果字符串bday{"err_code":0,"err_msg":"success","bday":"19920115"}
                Yayalog.loger( s.toString());
                mWebView.loadUrl("javascript:ApiGameCallBack.onVerifySuccess(" + s.toString() + ")");
                //{"uid":"4020895875512481162","username":"kk1411930146","token":"07518edabc40d63ec2acdae6b90924a4"}
             //   Yayalog.loger("Gameapi登陆成功：" + userjson.toString());
                //System.out.println("Gameapi登陆成功："+userjson.toString());
                //{"err_code":0,"err_msg":"success","bday":"19920115"}
             //   mWebView.loadUrl("javascript:ApiGameCallBack.loginSuc(" + userjson.toString() + ")");
            }

            @Override
            public void onVerifyCancel() {
                mWebView.loadUrl("javascript:ApiGameCallBack.onVerifyCancel()");
            }
        });
    }
}
